Skip to main content

Overview

The Knapsack problem is a classic optimization problem in computer science. The core idea is to maximize the total value of items that can fit into a knapsack of limited capacity without exceeding it.

Core Idea

  • Input:
    • A set of items, each a weight w, and a value v
    • A maximum weight capacity W for the knapsack
  • Output:
    • A subset of items that maximize the total value V such that total weight <= W

Resources

Variations

0/1 Knapsack

def findTargetSumWays(self, nums: List[int], target: int) -> int:
@lru_cache(None)
def dp(index, cur_sum):
if index >= len(nums) and cur_sum == target:
return 1
if index >= len(nums) and cur_sum != target:
return 0

positive = dp(index+1, cur_sum + nums[index])
negative = dp(index+1, cur_sum - nums[index])

return positive + negative

return dp(0, 0)

Fractional Knapsack

  • Items can be broken into smaller parts, allowing a fractional amount of an item to be included.
  • Solved using [[Greedy]] as the optimal solution involves taking items with the highest value-to-weight ration until the capacity is reached

Unbounded Knapsack

Bounded Knapsack

Multi-dimensional Knapsack

Subset Sum Problem

Knapsack with Conflicts